package com.mycompany.oj.service.Impl;

import com.mycompany.oj.Mapper.Impl.MyQuestionJudgeMapperImpl;
import com.mycompany.oj.Mapper.Impl.MyStudentMapperImpl;
import com.mycompany.oj.entity.*;
import com.mycompany.oj.service.StudentService;
import com.mycompany.oj.util.SharedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *
 * @author asus
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    MyStudentMapperImpl studentmapper;
    @Autowired
    MyQuestionJudgeMapperImpl questionJudgeMapper;
    @Autowired
    SharedService sharedService;

    @Value("${judge.compileCoursePath}")
    private String compileCoursePath;
    @Value("${judge.compilePath}")
    private String compilePath;
    @Value("${judge.errorPath}")
    private String errorPath;

    //获取个人信息
    //6.27改
    @Override
    public studentInformation getStudentInformationService(String id) {
        studentInformation studentInformation = new studentInformation();

        List<Map<String, Object>> temp = questionJudgeMapper.getAccountId(id);
        List<Map<String, Object>> temp2 = studentmapper.get_student_information(temp.get(0).get("id").toString());
        sharedService.mapToObject(studentInformation,temp2.get(0));
//        studentInformation.setGrade(temp2.get(0).get("grade").toString());
//        studentInformation.setMajor(temp2.get(0).get("major").toString());
//        studentInformation.setNickname(temp2.get(0).get("nickname").toString());
//        studentInformation.setSchool(temp2.get(0).get("school").toString());
//        studentInformation.setSchoolid(temp2.get(0).get("schoolid").toString());
//        studentInformation.setSex(temp2.get(0).get("sex").toString());
//        studentInformation.setStudent_name(temp2.get(0).get("student_name").toString());
        return studentInformation;
    }

    //修改手机号
    @Override
    public JsonResult changePhoneService(String newNumber, String username) {
        String account_id = sharedService.getAccountId(username);
        int i = studentmapper.changePhonenumber(newNumber, account_id);
        if (!sharedService.check1(String.valueOf(i)).equals("空")) {
            return new JsonResult(ResultCode.SUCCESS);
        }
        return new JsonResult(ResultCode.FAIL);
    }

    //修改密码
    @Override
    public JsonResult changePasswordService(String newpassword, String username) {
        String account_id = sharedService.getAccountId(username);
        int i = studentmapper.changePhonenumber(newpassword, account_id);
        if (!sharedService.check1(String.valueOf(i)).equals("空")) {
            return new JsonResult(ResultCode.SUCCESS);
        }
        return new JsonResult(ResultCode.FAIL);
    }

    //学生做题信息
    //6.27改
    @Override
    public StudentShowInformation showInformationService(String username) {
        String account_id = sharedService.getAccountId(username);

        StudentShowInformation temp = new StudentShowInformation();
        List<Map<String, Object>> temp1 = studentmapper.getPassNumber(account_id);
        List<Map<String, Object>> temp2 = studentmapper.getPostNumber(account_id);
        List<Map<String, Object>> temp3 = studentmapper.getTodayNumber(account_id);
        List<Map<String, Object>> temp4 = studentmapper.getPlanNumber(account_id);
        List<Map<String, Object>> temp5 = studentmapper.getLastAddress(account_id);

        //检查是否为空
        sharedService.check2(temp1);
        sharedService.check2(temp2);
        sharedService.check2(temp3);
        if (temp5.isEmpty()) {
            Map<String, Object> a = new HashMap();
            a.put("question_name", "A+B problem");
            temp5.add(a);
        }

//        temp.setPlan_number((int) temp4.get(0).get("plan_num"));
//        temp.setSchoolid((String) temp4.get(0).get("schoolid"));
//        temp.setUsername((String) temp4.get(0).get("nickname"));
        sharedService.mapToObject(temp,temp4.get(0));
        temp.setFinished_number(Integer.parseInt(temp3.get(0).get("number").toString()));
        temp.setPass_number(Integer.parseInt(temp1.get(0).get("number").toString()));
        temp.setPost_number(Integer.parseInt(temp2.get(0).get("number").toString()));
        if(!temp5.get(0).get("question_name").toString().equals("A+B problem"))
            temp.setLast_address(temp5.get(0).get("question_name").toString().substring(4));
        else
             temp.setLast_address(temp5.get(0).get("question_name").toString());
        //目前题目

        return temp;
    }

    public StudentShowInformation showInformationServiceT(String schoolid) {
        String account_id = sharedService.getAccountIdBySchoolid(schoolid);

        StudentShowInformation temp = new StudentShowInformation();
        List<Map<String, Object>> temp1 = studentmapper.getPassNumber(account_id);
        List<Map<String, Object>> temp2 = studentmapper.getPostNumber(account_id);
        List<Map<String, Object>> temp4 = studentmapper.getPlanNumber(account_id);
        List<Map<String, Object>> temp5 = studentmapper.getLastPostTime(account_id);
        List<Map<String, Object>> temp6 = studentmapper.lastSevenday(account_id);
        if (temp5.isEmpty()) {
            Map<String, Object> map = new HashMap<>();
            map.put("time", "0");
            temp5.add(map);
        }
        if (temp6.isEmpty()) {
            Map<String, Object> map = new HashMap<>();
            map.put("number", "0");
            temp6.add(map);
        }

        //检查是否为空
        sharedService.check2(temp1);
        sharedService.check2(temp2);

        temp.setSchoolid((String) temp4.get(0).get("schoolid"));
        temp.setUsername((String) temp4.get(0).get("nickname"));
        temp.setPass_number(Integer.parseInt(temp1.get(0).get("number").toString()));
        temp.setPost_number(Integer.parseInt(temp2.get(0).get("number").toString()));
        temp.setTime(temp5.get(0).get("time").toString());
        temp.setTime(temp6.get(0).get("number").toString());
        return temp;
    }

    //修改每日计划
    @Override
    public JsonResult changePlanService(String newnumber, String username) {
        if (sharedService.check1(String.valueOf(studentmapper.updatePlanNumber(username, newnumber))).equals("空")) {
            return new JsonResult(ResultCode.FAIL);
        }
        return new JsonResult(ResultCode.SUCCESS);
    }

    //概况
    @Override
    public QuestionFinishedNumber summarizeService(String username) {
        String account_id = sharedService.getAccountId(username);
        return doQuestionFinishedNumber(account_id);
    }

    public QuestionFinishedNumber summarizeTService(String schoolid) {
        String account_id = sharedService.getAccountIdBySchoolid(schoolid);
        return doQuestionFinishedNumber(account_id);
    }

    private QuestionFinishedNumber doQuestionFinishedNumber(String account_id) {
        QuestionFinishedNumber temp = new QuestionFinishedNumber();
        List<Map<String, Object>> all_number = studentmapper.getDifficultNumber();
        temp.setBasic(all_number.get(0).get("number").toString());
        temp.setMiddle(all_number.get(1).get("number").toString());
        temp.setDifficult(all_number.get(2).get("number").toString());
        if (all_number.get(3).get("number") == null) {
            temp.setVdifficult("0");
        } else {
            temp.setVdifficult(all_number.get(3).get("number").toString());
        }
        temp.setBasic_number(getNumber(studentmapper.questionNumber(account_id, "1")));
        temp.setBasic_number_Finished(getNumber(studentmapper.finishQuestionNumber(account_id, "1")));
        temp.setMiddle_number(getNumber(studentmapper.questionNumber(account_id, "2")));
        temp.setMidlle_number_Finished(getNumber(studentmapper.finishQuestionNumber(account_id, "2")));
        temp.setDifficult_number(getNumber(studentmapper.questionNumber(account_id, "3")));
        temp.setDifficult_number_Finished(getNumber(studentmapper.finishQuestionNumber(account_id, "3")));
        temp.setVdifficult_number(getNumber(studentmapper.questionNumber(account_id, "4")));
        temp.setVdifficult_number_Finished(getNumber(studentmapper.finishQuestionNumber(account_id, "4")));

        return temp;
    }

    //获取收藏夹
    //6.27改
    @Override
    public List<StudentFavorites> getFavoritesService(String username) {
        List<StudentFavorites> temp = new ArrayList<>();
        String account_id = sharedService.getAccountId(username);
        List<Map<String, Object>> my_favorites = studentmapper.getFavorites(account_id);
        List<Map<String, Object>> trueList = studentmapper.getTrueQuestion(account_id);
        List<Map<String, Object>> falseList = studentmapper.getFalseQuestion(account_id);
        for (Map<String, Object> my_favorite : my_favorites) {
            StudentFavorites favorites = new StudentFavorites();
            sharedService.mapToObject(favorites,my_favorite);
//            favorites.setQuestion_id(my_favorite.get("Question_id").toString());
//            favorites.setQuestion_name(my_favorite.get("question_name").toString());
            favorites.setQuestion_result(getResult(trueList, falseList, my_favorite.get("Question_id").toString()));
            temp.add(favorites);
        }
        return temp;
    }

    //删除收藏的题目
    @Override
    public JsonResult deleteQuestionService(String username, int question_id) {
        String account_id = studentmapper.getStudentId(username).get(0).get("id").toString();
        int temp = studentmapper.deleteQuestion(account_id, String.valueOf(question_id));
        if (sharedService.check1(String.valueOf(temp)).equals("空")) {
            return new JsonResult(ResultCode.FAIL);
        }
        return new JsonResult(ResultCode.SUCCESS);
    }

    //读取学生的做题number，为空则返回0
    private String getNumber(List<Map<String, Object>> temp) {
        if (temp.isEmpty()) {
            return "0";
        } else {
            return temp.get(0).get("question_num").toString();
        }
    }

    //判断收藏夹那道题的完成情况
    private String getResult(List<Map<String, Object>> tt, List<Map<String, Object>> ff, String id) {
        Stream<Map<String, Object>> temp1 = tt.stream().filter(x -> x.get("Question_id").equals(id));
        Stream<Map<String, Object>> temp2 = ff.stream().filter(x -> x.get("Question_id").equals(id));
        if (!temp1.collect(Collectors.toList()).isEmpty()) {
            return "True";
        } else if (!temp2.collect(Collectors.toList()).isEmpty()) {
            return "False";
        } else {
            return "null";
        }
    }

    //获取做题信息
    @Override
    public List<Map<String, Object>> getDifficultNum() {
        List<Map<String, Object>> basic = studentmapper.getDifficultNumber("1");
        List<Map<String, Object>> middle = studentmapper.getDifficultNumber("2");
        List<Map<String, Object>> difficult = studentmapper.getDifficultNumber("3");
        List<Map<String, Object>> veryDifficult = studentmapper.getDifficultNumber("4");
        List<Map<String, Object>> temp = new ArrayList<>();
        Map<String, Object> a = new HashMap<>();
        Map<String, Object> b = new HashMap<>();
        Map<String, Object> c = new HashMap<>();
        Map<String, Object> d = new HashMap<>();
        if (a.isEmpty()) {
            a.put("basic", "0");
        } else {
            a.put("basic", basic.get(0).get("num"));
        }
        if (b.isEmpty()) {
            b.put("basic", "0");
        } else {
            b.put("middle", middle.get(0).get("num"));
        }
        if (c.isEmpty()) {
            c.put("basic", "0");
        } else {
            c.put("difficult", difficult.get(0).get("num"));
        }
        if (d.isEmpty()) {
            d.put("basic", "0");
        } else {
            d.put("vdifficult", veryDifficult.get(0).get("num"));
        }
        temp.add(a);
        temp.add(b);
        temp.add(c);
        temp.add(d);
        return temp;
    }

    @Override
    public JsonResult changePersonalInformation(studentInformation student_information, String username) {
        String account_id = sharedService.getAccountId(username);
        //判空

        int temp = studentmapper.changeStudentInformation(student_information, account_id);
        if (sharedService.check1(String.valueOf(temp)).equals("空")) {
            return new JsonResult(ResultCode.FAIL);
        }
        return new JsonResult(ResultCode.SUCCESS);
    }

    //获取动态
    @Override
    public List<QuestionRegister> getFiveStudent(String username) {
        String account_id = sharedService.getAccountId(username);
        List<Map<String, Object>> temp = studentmapper.getFiveQuestion(account_id);
        return doGetFiveStudent(temp);
    }

    public List<QuestionRegister> getFiveStudentSchoolId(String schoolid) {
        String account_id = sharedService.getAccountIdBySchoolid(schoolid);
        List<Map<String, Object>> temp = studentmapper.getFiveQuestion(account_id);
        return doGetFiveStudent(temp);
    }

    private List<QuestionRegister> doGetFiveStudent(List<Map<String, Object>> temp) {
        List<QuestionRegister> list = new ArrayList<>();
        if (!temp.isEmpty()) {
            for (Map<String, Object> map : temp) {
                QuestionRegister question_Register = new QuestionRegister();
                question_Register.setQuestion_id(map.get("id").toString());
                question_Register.setQuestion_name(map.get("question_name").toString());
                String result;
                if (map.get("question_result").toString().equals("True")) {
                    result = "success";
                } else {
                    result = map.get("question_result").toString();
                }
                question_Register.setQuestion_result(result);
                question_Register.setQuestion_time(map.get("question_time").toString());
                list.add(question_Register);
            }
            return list;
        } else {
            return list;
        }
    }
    
    private void init(List<String> jingzhi){
        jingzhi.add("97");
        jingzhi.add("111");
        jingzhi.add("22");
        jingzhi.add("23");
        jingzhi.add("24");
        jingzhi.add("25");
        jingzhi.add("26");
        jingzhi.add("27");
        jingzhi.add("28");
        jingzhi.add("29");
        jingzhi.add("30");
        jingzhi.add("31");
        jingzhi.add("32");
        jingzhi.add("33");
    }

    //做题
    @Override
    public JsonResult practice(String file, String language, String question_name, String student_name, String status) {
        
        //status In为课程题目 out为题库内容
        int register_id;
        String question_id, student_id,localPath;
        student_id = studentmapper.getStudentId(student_name).get(0).get("id").toString();
        question_id = question_name;
        if (status.equals("in")) {  
            register_id = studentmapper.insertGoGoGoCourse(student_id, question_id);
            File newfile = new File("/root/Curse/" + String.valueOf(question_id) + "/" + String.valueOf(student_id));
            newfile.mkdir();
            localPath = "/root/Curse/" + String.valueOf(question_id) + "/" + String.valueOf(student_id);
        } else {
            register_id = studentmapper.insertGoGoGo(student_id, question_id);
            File newfile = new File("/root/Test/" + String.valueOf(question_id) + "/" + String.valueOf(student_id));
            newfile.mkdir();
            localPath = "/root/Test/" + String.valueOf(question_id) + "/" + String.valueOf(student_id);
        }
        List<String> jingzhi = new ArrayList<>();
        init(jingzhi);
        if(jingzhi.contains(question_name) && status.equals("in")){
            return new JsonResult(ResultCode.FAIL,"该题不支持提交");
        }
        
        

        // 要上传的目标文件存放路径
        String filename;
        if (language.equals("c")) {
            language = "LAN_CPP";
            filename = "Main.cpp";
        } else if (language.equals("c++")) {
            language = "LAN_CPP";
            filename = "Main.cpp";
        } else {
            language = "LAN_JAVA";
            filename = "Main.java";
        }
        File upFile = new File(localPath + "/" + filename);
        File errorFile = new File(localPath + "/error.txt");
        try {
            if (upFile.exists()) {
                upFile.delete();
            }
            upFile.createNewFile();
            if (errorFile.exists()) {
                errorFile.delete();
            }
            errorFile.createNewFile();
            Files.write(Paths.get(localPath + "/" + filename), file.getBytes());
        } catch (IOException ex) {
            Logger.getLogger(StudentServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        //FileUtils.upload(file, localPath, filename);

        //保存文件完成，开始编译
        try {
             String shpath;
            if(status.equals("in")){
               shpath = "/root/judge/compilecourse.sh " + register_id + " " + language + " " + localPath + "/" + filename + " " + question_id + " " + student_id;
            }else{
               shpath = "/root/judge/compile.sh " + register_id + " " + language + " " + localPath + "/" + filename + " " + question_id + " " + student_id;
            }
            Process ps = Runtime.getRuntime().exec(shpath);
            ps.waitFor();

            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            String result = sb.toString();
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String myresult;
        if (status.equals("in")) {
            myresult = studentmapper.getSpecifyResult(String.valueOf(register_id)).get(0).get("question_result").toString();
        } else {
            myresult = studentmapper.getAnSpecifyResult(String.valueOf(register_id)).get(0).get("question_result").toString();
        }
        if (myresult.equals("compilation fail")) {
            String errorpath = localPath + "/error.txt";
            try {
                Stream<String> stream = Files.lines(Paths.get(errorpath));
                List<String> result = stream.collect(Collectors.toList());
                if (!result.isEmpty()) {
                    return new JsonResult(ResultCode.FAIL, "编译失败", result);
                }
            } catch (IOException ex) {
                Logger.getLogger(StudentServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        List<Map<String, Object>> temp = new ArrayList<>();
        if (status.equals("in")) {
            temp = studentmapper.getTimeMemoryCourse(String.valueOf(register_id));
        } else {
            temp = studentmapper.getTimeMemory(String.valueOf(register_id));
        }
        return new JsonResult(ResultCode.SUCCESS, temp);
    }

    //获取测评数据
    public JsonResult doResult() {
        List<Map<String, Object>> temp = studentmapper.getResult();
        Collections.reverse(temp);
        return new JsonResult(ResultCode.SUCCESS, temp);
    }

    public JsonResult doPostAnswer(String student_id, String question_id, String answer, String language) {
        String[] temp = studentmapper.postAnswer(question_id, student_id, answer, language);
        if (temp.length == 0) {
            return new JsonResult(ResultCode.FAIL);
        } else {
            return new JsonResult(ResultCode.SUCCESS);
        }
    }

}
